﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class DiantaiUIView
{
    protected DiantaiMainCtr manager
    {
        get { return DiantaiMainCtr.Instance; }
    }

    protected RadioTagDataConfig localData
    {
        get { return RadioDataPool.Instance.localConfig; }
    }

    protected HUIFormScript m_Form;
    protected GameObject page_main;     //主页面
    protected GameObject page_play;     //播放页面
    protected GameObject page_buy;      //购买页面
    protected GameObject btn_return;    //返回按钮
    protected FMIndroduceCtr page_indroduce;

    protected GameObject template_tab_0;
    protected GameObject template_tab_1;
    public GameObject template_content_item0;
    protected GameObject template_page_item;

    protected GameObject btn_openURL;
    protected GameObject btn_fmClose;

    protected DiantaiPlay playUI;
    protected DiantaiUIBuy buyUI;
    protected GameObject loadingUI;

    protected Transform tab;
    protected Transform splitPage;
    protected List<GameObject> tabGameobjectList;
    protected List<int> tabInstanceIDlist;

    public List<GameObject> contentGameobjectList;
    public List<int> contentInstanceIDList;
    protected List<GameObject> splitPageGameobjectList;
    protected List<int> splitPageInstanceIDList;
    protected List<float> pageMinMaxList;

    public List<RadioTagViewItem> tabList = null;
    public List<RadioViewItem> contentList = null;
    protected int currentIndex = 1;         //当前tab索引 [0,1,2]
    protected int childPageIndex = 0;       //如果有内容  就表示为当前分页索引 [0,1,2]

    public Dictionary<GameObject, RadioViewItem> needSetImgcontentItem = new Dictionary<GameObject, RadioViewItem>();
    #region pageCache
    protected int clickedTabID;
    protected int clickedContentID;
    #endregion
    public void OpenForm()
    {
        //Debug.Log("UI.");
        if (m_Form != null && m_Form.gameObject != null)
        {
            RemoveLisenter();
            GameObject.DestroyImmediate(m_Form.gameObject);
        }
        m_Form = HUIManager.Instance.OpenForm(RadioDataPool.UIPath, false);
        InitForm();
        TimerManager.Instance.AddTimer(1000, -1, _pullContentItemImg);
    }

    protected void InitForm()
    {
        btn_return = m_Form.GetWidget("ButtonRtn");
        page_main = m_Form.GetWidget("Main");
        page_play = m_Form.GetWidget("Play");
        page_buy = m_Form.GetWidget("BuyForm");
        template_tab_0 = m_Form.GetWidget("Item_0");
        template_tab_1 = m_Form.GetWidget("Item_1");
        template_content_item0 = m_Form.GetWidget("Item_00");
        template_page_item = m_Form.GetWidget("Button");

        tab = page_main.transform.Find("Tab");
        splitPage = page_main.transform.Find("Content/content_2/pageItems");
        page_indroduce = page_main.transform.Find("FMIndroduce").GetComponent<FMIndroduceCtr>();
        page_indroduce.Init();

        //btn_openURL = m_Form.GetWidget("download_btn");
        btn_fmClose = m_Form.GetWidget("close_btn");

        loadingUI = m_Form.GetWidget("LoadingForm");

        HUIUtility.SetUIMiniEvent(btn_return, enUIEventType.Click, enUIEventID.Radio_Btn_Exit);
        
        Regester();


        //Debug.Log("InitForm over.");
    }
    
    int onePageNum = 6;
    public void AssembleUILayoutByData(int sum)
    {
        GridLayoutGroup gridLayoutGroup = template_content_item0.transform.parent.GetComponent<GridLayoutGroup>();
        float floatPageNum = sum / (onePageNum * 1.0f);
        int intPageNum = Mathf.CeilToInt(floatPageNum);

        float width = gridLayoutGroup.padding.left + gridLayoutGroup.padding.right + ((onePageNum / gridLayoutGroup.constraintCount) * (gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x)) * intPageNum;

        float width2 = gridLayoutGroup.padding.left + gridLayoutGroup.padding.right + Mathf.CeilToInt(sum * 1.0f / gridLayoutGroup.constraintCount) * (gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x) - gridLayoutGroup.spacing.x;

        //Debug.Log(string.Format("{0}/{1} {2}  固定行数:{3} {4}", 0, intPageNum, sum, gridLayoutGroup.constraintCount, width));
        RectTransform rect = (gridLayoutGroup.transform as RectTransform);
        rect.pivot = new Vector2(0f, 1f);
        rect.anchorMin = new Vector2(0f, 1f);
        rect.anchorMax = new Vector2(0f, 1f);
        rect.sizeDelta = new Vector2(width, (gridLayoutGroup.transform as RectTransform).sizeDelta.y);
    }

    protected void CaculateDefaultChoose()
    {
        bool find = false;
        for (int i = 0; i < tabList.Count; i++)
        {
            if (tabList[i].hoverThisWhenLoad)
            {
                currentIndex = i;
                find = true;
                return;
            }
        }
        if (!find) currentIndex = 0;
    }

    public void UpdateData()
    {
        Debug.Log("111");
        tabInstanceIDlist = new List<int>();
        tabList = RadioDataPool.Instance.GetTabData();
        
        CaculateDefaultChoose();
        if (tabGameobjectList == null) tabGameobjectList = new List<GameObject>();
        int len1 = tabList.Count;
        int len2 = tabGameobjectList.Count;
        int sum = Mathf.Max(len1, len2);
        GameObject tabTemplate = null;
        for (int i = 0; i < sum; i++)
        {
            RadioTagViewItem dataItem = null;
            if (i >= len1)
            {
                //数据已越界
                if (i >= len2)
                {
                    //..
                }
                else
                {
                    tabGameobjectList[i].SetActive(false);
                }
            }
            else
            {
                dataItem = tabList[i];
                if (i >= len2)
                {
                    if (dataItem.state == RadioTagViewState.rainBallFM)
                    {
                        tabTemplate = template_tab_0;
                    }
                    else
                    {
                        tabTemplate = template_tab_1;
                    }
                    GameObject tabItem = GameObject.Instantiate(tabTemplate);
                    tabItem.SetActive(true);
                    tabGameobjectList.Add(tabItem);
                    tabItem.transform.SetParent(tab, false);
                    tabItem.GetComponent<Toggle>().onValueChanged.RemoveAllListeners();
                    tabItem.GetComponent<Toggle>().onValueChanged.AddListener(OnValueChange);
                    tabInstanceIDlist.Add(tabItem.GetInstanceID());
                    UpdateTabItem(tabItem, dataItem);
                }
                else
                {
                    tabGameobjectList[i].SetActive(true);
                    UpdateTabItem(tabGameobjectList[i], dataItem);
                }
            }
        }
        tab.GetComponent<HorizontalLayoutGroup>().SetLayoutHorizontal();
        IntelligentClick();
    }

    public void RefreshUI()
    {
        IntelligentClick();
    }

    public void OnPopFailed()
    {
        this.FmCloseBtnClick();
    }

    protected void UpdateTabItem(GameObject tabItem, RadioTagViewItem dataItem)
    {
        //Debug.Log(dataItem.localImgPath);
        Image unSelectImg = tabItem.transform.Find("off_img").GetComponent<Image>();
        Image selectImg = tabItem.transform.Find("on_img/Image").GetComponent<Image>();
        RectTransform rect = selectImg.transform as RectTransform;
        Text title = tabItem.transform.Find("Text").GetComponent<Text>();
        RadioUIHelper.SetImg(selectImg, dataItem.localImgPath, rect.rect, dataItem.defaultTex);
        RadioUIHelper.SetImg(unSelectImg, dataItem.localImgPath, rect.rect, dataItem.defaultTex);
        title.text = dataItem.nameStr;
    }


    protected void IntelligentClick()
    {
        tabGameobjectList[currentIndex].GetComponent<Toggle>().isOn = true;
        tabGameobjectList[currentIndex].GetComponent<Toggle>().onValueChanged.Invoke(true);
    }

    protected void OnValueChange(bool isOn)
    {
        if (!isOn) return;
        IEnumerable toggles = tab.GetComponent<ToggleGroup>().ActiveToggles();
        
        foreach (Toggle tog in toggles)
        {
            int instanceID = tog.gameObject.GetInstanceID();
            if (tabInstanceIDlist.Contains(instanceID))
            {
                int i = tabInstanceIDlist.IndexOf(instanceID);
                UpdateContent(i);
                currentIndex = i;
                _pullTabImg();
                YOUMENG(i);
                return;
            }
        }
    }

    protected void YOUMENG(int ID)
    {
        RadioTagViewItem tabItem = tabList[ID];
        if (tabItem.state== RadioTagViewState.normal)
            SDKManager.Instance.Event((UmengEvent)tabItem.tag);
    }

    protected void UpdateContent(int instanceIDIndex)
    {
        
        RadioTagViewItem tabItem = tabList[instanceIDIndex];
        clickedTabID = tabItem.tag;//
        if (tabItem.state == RadioTagViewState.rainBallFM)
        {
            InitFmContent();
            //HideTab();
            HideReturnBtn();
        }
        else
        {
            InitNormalContent(instanceIDIndex);
            
        }
    }

    protected void HideTab()
    {
        tab.gameObject.SetActive(false);
    }

    protected void HideReturnBtn(bool hide = true)
    {
        btn_return.SetActive(!hide);
    }

    protected void FmCloseBtnClick()
    {
        tab.gameObject.SetActive(true);
        currentIndex = 1;
        IntelligentClick();
        HideReturnBtn(false);
    }

    protected void InitFmContent()
    {
        //初始化FM推荐内容.
        Debug.Log("Fm");

    }
    
    protected void InitNormalContent(int index)
    {
        DiantaiUIPatch.Instance.LoadMainUI(this, index);
        //contentInstanceIDList = new List<int>();
        //needSetImgcontentItem.Clear();
        //if (contentGameobjectList == null) contentGameobjectList = new List<GameObject>();
        //contentList = RadioDataPool.Instance.GetViewData(tabList[index].tag);
        //int len1 = contentGameobjectList.Count;
        //int len2 = contentList.Count;
        //int sum = Mathf.Max(len1, len2);
        //
        //AssembleUILayoutByData(len2);
        //for (int i = 0; i < sum; i++)
        //{
        //    if (i >= len2)
        //    {
        //        if (i >= len1)
        //        {
        //            //
        //        }
        //        else
        //        {
        //            contentGameobjectList[i].SetActive(false);
        //        }
        //    }
        //    else
        //    {
        //        if (i >= len1)
        //        {
        //            GameObject tmp = GameObject.Instantiate(template_content_item0);
        //            tmp.SetActive(true);
        //            tmp.transform.SetParent(template_content_item0.transform.parent, false);
        //
        //            contentGameobjectList.Add(tmp);
        //
        //            UpdateContentItem(tmp, contentList[i]);
        //            contentInstanceIDList.Add(tmp.GetInstanceID());
        //        }
        //        else
        //        {
        //            contentGameobjectList[i].SetActive(true);
        //            UpdateContentItem(contentGameobjectList[i], contentList[i]);
        //            contentInstanceIDList.Add(contentGameobjectList[i].GetInstanceID());
        //        }
        //    }
        //}
        //
        //
        //template_content_item0.transform.parent.GetComponent<GridLayoutGroup>().SetLayoutHorizontal();
        
    }

    public void InitSplitPage()
    {
        splitPageInstanceIDList = new List<int>();
        if (splitPageGameobjectList == null) splitPageGameobjectList = new List<GameObject>();
        int length = contentList.Count;
        float floatPageNum = length / (onePageNum * 1.0f);
        int intPageNum = Mathf.CeilToInt(floatPageNum);

        int len1 = splitPageGameobjectList.Count;
        int len2 = intPageNum;
        int sum = Mathf.Max(len1, len2);
        for (int i = 0; i < sum; i++)
        {
            if (i >= len2)
            {
                if (i >= len1)
                {
                    //.
                }
                else
                {
                    splitPageGameobjectList[i].GetComponent<Toggle>().isOn = (i == 0 ? true : false);
                    splitPageGameobjectList[i].SetActive(false);
                }
            }
            else
            {
                if (i >= len1)
                {
                    GameObject tmp = GameObject.Instantiate(template_page_item);
                    tmp.GetComponent<Toggle>().isOn = (i == 0 ? true : false);
                    tmp.SetActive(true);
                    tmp.transform.SetParent(template_page_item.transform.parent, false);

                    tmp.GetComponent<Toggle>().onValueChanged.RemoveAllListeners();
                    tmp.GetComponent<Toggle>().onValueChanged.AddListener(OnValueChange_SplitPage);

                    splitPageGameobjectList.Add(tmp);
                    splitPageInstanceIDList.Add(tmp.GetInstanceID());
                }
                else
                {
                    splitPageGameobjectList[i].GetComponent<Toggle>().isOn = (i == 0 ? true : false);
                    splitPageGameobjectList[i].SetActive(true);
                    splitPageInstanceIDList.Add(splitPageGameobjectList[i].GetInstanceID());
                }
            }
        }

        InitSplitMinMax(splitPageInstanceIDList.Count);
        _move2page(0);
    }

    protected void InitSplitMinMax(int length)
    {
        GridLayoutGroup gridLayoutGroup = template_content_item0.transform.parent.GetComponent<GridLayoutGroup>();
        float anchorWidth = (gridLayoutGroup.transform.parent as RectTransform).rect.width;
        float mywidth = (gridLayoutGroup.transform as RectTransform).rect.width;
        int tmp = onePageNum / gridLayoutGroup.constraintCount;
        float onewidth = tmp * (gridLayoutGroup.cellSize.x + gridLayoutGroup.spacing.x);
        float left = gridLayoutGroup.padding.left;
        float right = gridLayoutGroup.padding.right;
        pageMinMaxList = new List<float>() { 0};
        if (length >= 2)
            for (int i = 1; i < length; i++)
            {
                if (i == length - 1)
                    pageMinMaxList.Add(anchorWidth - mywidth);
                else
                {
                    if (i == 1)
                        pageMinMaxList.Add(pageMinMaxList[i - 1] - left - onewidth);
                    else
                        pageMinMaxList.Add(pageMinMaxList[i - 1] - onewidth);
                }
            }
    }

    protected void OnValueChange_SplitPage(bool isOn)
    {
        if (!isOn) return;

        IEnumerable toggles = splitPage.GetComponent<ToggleGroup>().ActiveToggles();
        foreach (Toggle tog in toggles)
        {
            int instanceID = tog.gameObject.GetInstanceID();
            if (splitPageInstanceIDList.Contains(instanceID))
            {
                _move2page(splitPageInstanceIDList.IndexOf(instanceID));
                return;
            }
        }
    }

    //内容页移动到相关位置
    protected void _move2page(int index)
    {
        //Debug.Log("移动到 " + index);
        RectTransform rect = template_content_item0.transform.parent.GetComponent<RectTransform>();
        rect.anchoredPosition = new Vector2(pageMinMaxList[index], rect.anchoredPosition.y);
    }

    public void UpdateContentItem(GameObject contentItem, RadioViewItem dataItem)
    {
        GameObject xianmian = contentItem.transform.Find("xianmian_tag").gameObject;
        GameObject weigoumai = contentItem.transform.Find("weigoumai_tag").gameObject;
        GameObject gouwuche = weigoumai.transform.Find("gouwuche_tag").gameObject;
        Image img = contentItem.transform.Find("cover_mask/cover").GetComponent<Image>();
        img.sprite = null;
        RadioTextScroll radioTextScroll = contentItem.transform.Find("Image").GetComponent<RadioTextScroll>();
        GameObject loading = contentItem.transform.Find("loading").gameObject;
        if (FileTools.IsFileExist(dataItem.imgLocalPath))
        {
            loading.SetActive(false);
        }
        else
        {
            if (!loading.activeInHierarchy) loading.SetActive(true);
            needSetImgcontentItem[contentItem] = dataItem;
        }

        RadioUIHelper.SetImg(img, dataItem.imgLocalPath, RadioDataPool.imgRect);
        if (dataItem.itemState == 1)//1免费 0付费
        {
            xianmian.SetActive(false);
            weigoumai.SetActive(false);
        }
        else if (dataItem.itemState == 0)
        {
            xianmian.SetActive(false);
            weigoumai.SetActive(true);
        }

        radioTextScroll.Inject(dataItem.nameStr);

        contentItem.GetComponent<Button>().onClick.RemoveAllListeners();
        contentItem.GetComponent<Button>().onClick.AddListener(() =>
        {
            ContentItemClick(contentItem.GetInstanceID());
        });
    }

    int goods_id;
    protected void ContentItemClick(int instanceID)
    {
        if (contentInstanceIDList.Contains(instanceID))
        {
            int index = contentInstanceIDList.IndexOf(instanceID);
            RadioViewItem tmp = contentList[index];
            clickedContentID = index;
            if (tmp.itemState == 0)
            {
                Cmd.Album album = RadioDataPool.Instance.GetTabDataById(tmp.leadershipTag);
                if (album != null)
                {
                    goods_id = album.good_id;
                    Debug.Log("<color=green>"+album.good_id+"</color>");
                    //OpenBuyForm(album.good_id);
                    PayManager.Instance.Pay(album.good_id, _callback);
                }
                // OpenBuyForm(album.cid);
                else
                    Debug.LogError("Album null. " + tmp.leadershipTag);
            }
            else
            {
                OpenPlayForm();
            }
        }
    }

    protected void _callback(int a, bool b)
    {
        Debug.Log(string.Format("a:{0} b:{1}", a, b));

        if (b)
            RadioDataPool.Instance.BuyAlbumSuccess(goods_id);

        DiantaiMainCtr.Instance.RefreshUI();

    }

    protected void OpenBuyForm(int goodId)
    {
        if (page_buy.GetComponent<DiantaiUIBuy>() == null) buyUI = page_buy.AddComponent<DiantaiUIBuy>();
        buyUI.InjectData(goodId);
        page_buy.SetActive(true);
    }

    protected void OpenPlayForm()
    {
        if (page_play.GetComponent<DiantaiPlay>() == null) playUI = page_play.AddComponent<DiantaiPlay>();
        string json = RadioDataPool.Instance.GetJsonByTabID(clickedTabID);
        List<RadioViewItem> list = RadioDataPool.Instance.GetPlayList(clickedTabID);

        playUI.InjectData(json, clickedContentID,list);
        page_play.SetActive(true);
    }

    protected void ScrollMove(HUIEvent hUIEvent)
    {
        if(pageMinMaxList!=null && pageMinMaxList.Count>1)
        UpdateSplitPage(hUIEvent.m_eventParams.argFloat);
    }

    protected void NetLoading(HUIEvent hUIEvent)
    {
        loadingUI.SetActive(hUIEvent.m_eventParams.argInt == 0);
    }

    protected void UpdateSplitPage(float content_x)
    {
        RectTransform rect = template_content_item0.transform.parent.GetComponent<RectTransform>();
        if (ScrollRectPatch.horizontal < 0f)
            for (int i = 0; i < pageMinMaxList.Count; i++)
            {
                bool find = false;
                if (i < (pageMinMaxList.Count - 1))
                    if (content_x < pageMinMaxList[i] && content_x > pageMinMaxList[i + 1])
                        find = true;
                if (i == pageMinMaxList.Count - 1)
                    if (content_x < pageMinMaxList[i])
                        find = true;

                if (find)
                {
                    Toggle tgg = splitPageGameobjectList[i].GetComponent<Toggle>();
                    if (!tgg.isOn)
                        splitPageGameobjectList[i].GetComponent<Toggle>().isOn = true;
                    break;
                }
            }
        else if(ScrollRectPatch.horizontal>0f)
            for (int i = pageMinMaxList.Count-1; i >=0; i--)
            {
                bool find = false;
                if (i == 0)
                    if (content_x > pageMinMaxList[i])
                        find = true;
                if (i > 0)
                    if (content_x < pageMinMaxList[i - 1] && content_x > pageMinMaxList[i])
                        find = true;
                
                if (find)
                {
                    Toggle tgg = splitPageGameobjectList[i].GetComponent<Toggle>();
                    if (!tgg.isOn)
                        splitPageGameobjectList[i].GetComponent<Toggle>().isOn = true;
                    break;
                }
            }
    }

    //拉取tab Img
    protected void _pullTabImg()
    {
        //
        for (int i = 2; i < tabList.Count; i++)
        {
            if (tabGameobjectList[i] != null)
            {
                Image unSelectImg = tabGameobjectList[i].transform.Find("off_img").GetComponent<Image>();
                Image selectImg = tabGameobjectList[i].transform.Find("on_img/Image").GetComponent<Image>();
                RectTransform rect = selectImg.transform as RectTransform;
                RadioUIHelper.SetImg(selectImg, tabList[i].localImgPath, rect.rect, tabList[i].defaultTex);
                RadioUIHelper.SetImg(unSelectImg, tabList[i].localImgPath, rect.rect, tabList[i].defaultTex);
            }
        }
    }

    //拉取contentItem Img
    protected void _pullContentItemImg(int sequence)
    {
        if (needSetImgcontentItem.Count > 0)
        {
            GameObject[] gameObjects = new GameObject[needSetImgcontentItem.Count];
            needSetImgcontentItem.Keys.CopyTo(gameObjects, 0);
            foreach (var go in gameObjects)
            {
                if (FileTools.IsFileExist(needSetImgcontentItem[go].imgLocalPath))
                {
                    //setup
                    //remove
                    RadioViewItem dataItem = needSetImgcontentItem[go];
                    GameObject contentItem = go;
                    Image img = contentItem.transform.Find("cover_mask/cover").GetComponent<Image>();
                    GameObject loading = contentItem.transform.Find("loading").gameObject;
                    RadioUIHelper.SetImg(img, dataItem.imgLocalPath, RadioDataPool.imgRect);
                    loading.SetActive(false);
                    needSetImgcontentItem.Remove(go);
                }
            }
        }
    }

    public void UrlBtnClick()
    {
        RadioDataPool.Instance.Jump2DownloadURL();
    }

    public void CloseForm()
    {
        
        if (!m_Form.IsClosed()) HUIManager.Instance.CloseForm(m_Form);
    }

    public void Clear()
    {
        RemoveLisenter();
    }

    #region 事件
    void Regester()
    {
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Radio_Net_Loading, NetLoading);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Radio_Scroll_Move, ScrollMove);
        //btn_openURL.GetComponent<Button>().onClick.AddListener(UrlBtnClick);
        btn_fmClose.GetComponent<Button>().onClick.AddListener(FmCloseBtnClick);
    }

    void RemoveLisenter()
    {
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Radio_Net_Loading, NetLoading);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Radio_Scroll_Move, ScrollMove);
        //btn_openURL.GetComponent<Button>().onClick.RemoveAllListeners();
        btn_fmClose.GetComponent<Button>().onClick.RemoveListener(FmCloseBtnClick);
    }
    
    #endregion
}